<template>
  <div class="customer-wrap">
    <div class="custom-title">
      <!-- 快捷搜索 -->
      <div class="quickSearch">
        <el-dropdown @command="quickSearchHandleCommand">
          <span class="el-dropdown-link">
            {{ currentSource.label }}<i class="el-icon-arrow-down el-icon--right"></i>
          </span>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item v-for="v in sourceList" :key="v.label" :command="v"> {{ v.label }}</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </div>
      <!-- 搜索框 -->
      <el-popover
        placement="top-start"
        ref="popoverRef"
        popper-class="search-popover"
        width="500"
        v-model="searchListVisible"
        trigger="manual"
      >
        <SearchList
          ref="searchListRef"
          class="search-list"
          @updateList="updateList"
          :keywords="keywords"
        />
        <el-input
          class="mar-l-10"
          style="width: 160px; font-weight: 500"
          :placeholder="$t('im.imChat.components.customerList.pla1')"
          prefix-icon="el-icon-search"
          clearable
          v-model="keywords"
          @input="keywordInput"
          @keydown.enter.native="keywordInput"
          slot="reference"
        >
        </el-input>
      </el-popover>
      <!-- 高级筛选 -->
      <div class="filterBox">
        <span
          @click="visible = true"
          class="iconfont icon-filter filter"
        ></span>
      </div>
    </div>
    <div class="conversation-card">
      <!-- 排队会话 -->
      <div class="conversation-card-item" v-if="!ConversationInfo.currentLineNum">
        <span>{{ ConversationInfo.currentLineNum }}</span>
        <span>{{ $t('common.pageTitle.pageConversationLine') }}</span>
      </div>
      <el-popover 
        v-else
        placement="bottom-start"
        width="300"
        trigger="hover"
        popper-class="conversation-popover"
        @show="handleLinePopoverShow"
        @hide="handleLinePopoverHide"
      >
        <div class="line-popover">
          <div>
            {{ $t('im.imChat.components.customerList.tips5') }}
            <i18n path="common.base.somePerson">
              <span class="highlight" place="data1">{{ ConversationInfo.currentLineNum }}</span>
            </i18n>
          </div>
          <div
            v-for="item in ConversationInfo.currentLineConversation"
            :key="item.conversationId"
            class="line-item"
          >
            <div>
              <Avatar mode="customer" :item="item" :size="20" />
              <span class="name">{{ item.conversationSponsorName }}</span>
            </div>
            <div>
              <span>{{ getDiffTime(item.conversationStartTime) }}</span>
              <!-- <el-button type="text" @click="lineIntervene">
                {{ $t('im.imChat.components.customerList.tips7') }}
              </el-button> -->
            </div>
          </div>
        </div>
        <div class="conversation-card-item active" slot="reference">
          <span>{{ ConversationInfo.currentLineNum }}</span>
          <span>{{ $t('common.pageTitle.pageConversationLine') }}</span>
        </div>
      </el-popover>
      <!-- 机器人会话 -->
      <div class="conversation-card-item" v-if="!ConversationInfo.robotConversationNum">
        <span>{{ ConversationInfo.robotConversationNum }}</span>
        <span>{{ $t('im.imChat.components.customerList.tips6') }}</span>
      </div>
      <el-popover 
        v-else
        placement="bottom-start"
        width="300"
        trigger="hover"
        popper-class="conversation-popover"
        @show="handleLinePopoverShow"
        @hide="handleLinePopoverHide"
      >
        <div class="line-popover">
          <div>
            {{ $t('im.imChat.components.customerList.tips6') }}
            <i18n path="common.base.somePerson">
              <span class="highlight" place="data1">{{ ConversationInfo.robotConversationNum }}</span>
            </i18n>
          </div>
          <div
            v-for="item in ConversationInfo.currentRobotConversation"
            :key="item.conversationId"
            class="line-item"
          >
            <div>
              <Avatar mode="robot" :size="20" />
              <span class="name">{{ item.conversationSponsorName }}</span>
            </div>
            <div>
              <span>{{ getDiffTime(item.conversationStartTime) }}</span>
              <el-button type="text" @click="robotIntervene(item.conversationId)">
                {{ $t('im.imChat.components.customerList.tips7') }}
              </el-button>
            </div>
          </div>
        </div>
        <div class="conversation-card-item active" slot="reference">
          <span>{{ ConversationInfo.robotConversationNum }}</span>
          <span>{{ $t('im.imChat.components.customerList.tips6') }}</span>
        </div>
      </el-popover>
      <!-- 已完成 -->
      <div class="conversation-card-item">
        <span>{{ ConversationInfo.todayDealNum }}</span>
        <span>{{ $t('common.task.type.finished') }}</span>
      </div>
    </div>
    <div v-if="customerList && customerList.length > 0">
      <div class="wrap">
        <div class="wrap-title">{{ $t('product.component.qrcodeDialog.text1') }} {{ ConversationInfo.currentConversationNum }}</div>
        <div
          v-for="(item, index) in customerList"
          :key="index"
          class="customer-item"
          :class="{ addColor: index == isactive }"
          @click="clickCustomer(item, index)"
          @contextmenu.prevent="onContextmenu($event,item)"
        >
          <div v-if="item.topSort" class="Topping"></div>
          <!-- 删除 -->
          <div class="im-delete" @click.stop="click(item.id)">
            <i class="iconfont icon-fe-close"></i>
          </div>
          <!-- 头像 -->
          <Avatar mode="customer" :item="item" :size="40" />
          <!-- 消息未读数 -->
          <div
            class="im-msg"
            v-if="index != isactive && item.unreadCount != 0"
            :class="
            item.unreadCount > 99 ? 'im-big-count' : 'im-small-count'
            ">
            {{ item.unreadCount | unreadCountFilter }}
          </div>
          <div class="item-info">
            <div class="im-name">
              <span class="user-name">{{ item.titleName }}</span>
              <span :class="['iconfont','tag-icon', getTagIcon(item)]" v-if="item.titleName && getTagIcon(item)"></span>
              <span class="im-recentTime">{{formatDate(item.recentTime, 'MM-DD')}}</span>
            </div>
            <!-- 最近一条消息 -->
            <div class="im-recentMessage">
              {{ item.recentMessage}}
            </div>
            <div class="tag-box">
              <span class="tag tag-ygq" v-if="item.isTimeOut"
              ><span>{{$t('common.base.timedOut')}}</span></span
              >
              <span class="tag tag-yjs" v-else-if="item.conversationStatus === 3"
              ><span>{{$t('common.base.usualStatus.haveFinished')}}</span></span
              >
              <span
                class="tag tag-ygq"
                v-else-if="item.timeOut && item.conversationStatus != 3"
              ><span>{{$t('common.base.usualStatus.expired')}}</span></span
              >
            </div>
          </div>
        </div>
        <div class="load-more" v-if="hasNextPage" @click="loadMoreData">
          {{$t('common.base.tip.loadMore')}}
        </div>
      </div>
    </div>

    <div v-else class="default">
      <div class="default-img">
        <img :src="noDataImage" alt="" />
      </div>
      <div class="default-msg">{{$t('im.imChat.components.customerList.tips4')}}</div>
    </div>

    <!-- 高级搜索框 -->
    <base-search-drawer
      :show.sync="visible"
      :storage-key="advancedColumnNumStorageKey"
      @reset="resetParams"
      @search="search([], true)"
      @changeWidth="setAdvanceSearchColumn"
      @getColumnNum="setAdvanceSearchColumn"
    >
      <base-search-panel
        ref="searchPanel"
        :column-num="columnNum"
        :fields="advanceSearchColumn"
      />
    </base-search-drawer>
  </div>
</template>
<script>
import * as IMApi from '@src/api/ImApi.js';
import { formatDate } from 'pub-bbx-utils';
import BaseSearchDrawer from 'packages/BaseSearchDrawer';
import BaseSearchPanel from 'packages/BaseSearchPanel';
import { getAdvancedFields } from './fields';
import { getRootWindow } from '@src/util/dom';
/* enum */
import StorageKeyEnum from '@model/enum/StorageKeyEnum.ts';
import { safeNewDate } from '@src/util/time';
import { SessionSourceMap } from '@model/enum/ImEnum.js'

import AuthMixin from '@src/mixins/authMixin';
import SearchList from '@src/modules/im/imChat/components/costomList/searchList.vue'
import moment from 'moment';
import { getOssUrl } from '@src/util/assets'
import Avatar from '@src/modules/im/imChat/components/messageBox/chattingRecords/components/Avatar.vue'

const noDataImage = getOssUrl('/no_data.png')
export default {
  name: 'customer-list',
  mixins: [AuthMixin],
  props: {
    customerList: {
      type: Array,
      default: () => [],
    },
    customerServiceNumber: {
      type: String,
    },
    ConversationInfo: {
      type: Object,
      default: () => {},
    },
    hasNextPage: {
      type: Boolean,
      default: () => true,
    },
  },
  data() {
    return {
      noDataImage,
      isactive: -1,
      loading: false,
      visible: false,
      advancedColumnNumStorageKey: StorageKeyEnum.IMListAdvancedColumnNum,
      columns: [],
      columnNum: 1,
      AllPutChannel: [],
      keywords: '',
      keywordTime: null,
      searchListVisible: false,
      currentTime: new Date(),
      linePopoverShow: false,
      timer: null,
      currentSource: '',
      sourceList: [],
    };
  },
  filters: {
    formatDate(value) {
      return formatDate(value, 'YYYY-MM-DD HH:mm:ss');
    },
    unreadCountFilter(value) {
      return value > 99 ? '99+' : value;
    },
    InitializationTime(value) {
      if (typeof value === 'string') {
        let time = value.slice(0, 19);
        // safeNewDate().getTimezoneOffset() 获取的是当前时区 小时 乘 60 分钟的值
        return (
          safeNewDate(time).getTime()
          + safeNewDate().getTimezoneOffset() * 60 * 1000 * -1
        );
      }
      return value;
    },
  },
  methods: {
    robotIntervene(id) {
      if (!id) return;

      IMApi.transferToLabor({
        conversationId: id,
      }).then(res => {
        if (res.code === 0) {
          this.$message({
            message: this.$t('im.detail.tips4'),
            type: 'success',
          });
          // 重新刷新数据
          this.search();
        } else {
          this.$message.error(res.message);
        }
      });
    },
    formatDate,
    loadMoreData() {
      this.$emit('loadMoreData');
    },
    clickCustomer(item, index) {
      // 用于全局通知判断，记录当前开启页面
      sessionStorage.setItem('CurrentCustomerInfor', JSON.stringify(item));
      this.isactive = index;
      this.$emit('clickCustomer', item, index);
    },
    click(id) {
      this.$emit('deleteIm', { id });
    },
    // 获取渠道列表
    getAllPutChannel() {
      IMApi.getAllPutChannel().then(res => {
        const { code, message = this.$t('common.base.tip.systemIsError'), data = [] } = res;
        if (code !== 0) return this.$platform.alert(message);
        this.AllPutChannel = data.map(item => {
          item.text = item.channelName;
          item.value = item.id;
          return item;
        });
      });
    },
    Operation(type, info) {
      switch (type) {
      case 'Topping': {
        // 置顶
        IMApi.conversationTop({
          customerServiceNumber: this.customerServiceNumber,
          conversationId: info.id,
        }).then(res => {
          if (res.code === 0) {
            this.$emit('updateList');
          }
        });
        break;
      }
      case 'CancelTopping': {
        // 取消置顶
        IMApi.cancelConversationTop({
          customerServiceNumber: this.customerServiceNumber,
          conversationId: info.id,
        }).then(res => {
          if (res.code === 0) {
            this.$emit('updateList');
          }
        });
        break;
      }
      case 'Hide': {
        // 隐藏
        this.click(info.id);
        break;
      }
      }
      const trackObj = {
        Topping: {
          id: 'TOPPING_SESSION',
          data: 'TOP'
        },
        CancelTopping: {
          id: 'TOPPING_SESSION',
          data: 'UNTOP'
        },
        Hide: {
          id: 'HIDE_SESSION',
        }
      }
      this.$track.clickStat(this.$track.formatParams(trackObj[type].id, trackObj[type].data));
    },
    // 重置
    resetParams() {
      const fromId = window.frameElement.getAttribute('id');
      this.$platform.refreshTab(fromId);
    },
    // 设置高级搜索展示列数
    setAdvanceSearchColumn(command) {
      this.columnNum = Number(command);
    },
    // 搜索框
    search(idList = [], isAdvancedSearch = false, isQuickSearch = false) {
      // 获取高级搜索参数
      let advancedSearchParams = this.$refs.searchPanel
        ? this.$refs.searchPanel.buildParams()
        : {};
      // 渠道接收数组类型
      if (advancedSearchParams.putChannelIds) {
        advancedSearchParams.putChannelIds = [
          advancedSearchParams.putChannelIds,
        ];
      }
      if(isQuickSearch) {
        advancedSearchParams.source = this.currentSource.value
      }
      this.visible = false;
      const params = {
        ...advancedSearchParams,
        keywords: idList.length > 0 ? '' : this.keywords,
        conversationIdList: idList,
      }
      if (!this.keywords) {
        params.conversationStatus = isAdvancedSearch ? params.conversationStatus : 2;
      }
      this.$emit('updateParamsSearch', params);
      this.$emit('updateList');
    },
    keywordInput(value) {
      if (this.keywordTime) clearTimeout(this.keywordTime);
      this.keywordTime = setTimeout(async () => {
        this.isactive = -1;
        if (this.keywords.trim()) {
          await this.$refs?.searchListRef?.getComprehensiveSearch(this.keywords);
          this.$refs.searchPanel?.initFormVal();
        } else {
          this.search();
        }

        this.searchListVisible = !!this.keywords.trim();
        clearTimeout(this.keywordTime);
      }, 1000);
    },
    hidePopover(e) {
      if(e.target.className !== 'search-list'){
        this.searchListVisible = false;
      }
    },
    updateList(item) {
      this.searchListVisible = false;
      let idList = [];
      if (item.conversationId) {
        idList.push(item.conversationId);
      } else {
        idList = item.conversationIdList;
      }

      this.search(idList);
    },
    getDiffTime(time) {
      const timestamp = moment(this.currentTime).diff(time);
      const hour = moment(this.currentTime).diff(time, 'hour');

      return `${hour}:${moment(timestamp).format('mm:ss')}`;
    },
    handleLinePopoverShow() {
      this.linePopoverShow = true;
    },
    handleLinePopoverHide() {
      this.linePopoverShow = false;
      this.timer = null;
    },
    onContextmenu(event,item) {
      this.$contextmenu({
        items: [
          {
            label: this.$t('common.base.topping'),
            onClick: () => {
              this.Operation('Topping', item)
            },
            hidden:item.topSort
          },
          {
            label: this.$t('common.base.cancelTopping'),
            onClick: () => {
              this.Operation('CancelTopping', item)
            },
            hidden:!item.topSort
          },
          {
            label: this.$t('common.base.hide'),
            onClick: () => {
              this.Operation('Hide', item)
            }
          },
        ],
        event,
        customClass: "im-operation-list",
        zIndex: 3,
      });
      return false;
    },
    getTagIcon(item) {
      const { source } = item
      if(source == 'weChat') return 'icon-weixin5'
      if(source == 'emailService') return 'icon-mail-fill1'
      return ''
    },
    quickSearchHandleCommand(val) {
      this.currentSource = val;
      this.search([], true, true)
    },
    setSourceList() {
      const baseSource = [
        { key: 'all', label: this.$t('common.fields.customerRegisteredSource.options.all'), value: '' },
        { key: 'im', label: SessionSourceMap['im'], value: 'im' },
        { key: 'weChat', label: SessionSourceMap['weChat'], value: 'weChat' },
      ]
      if(this.isOpenMailIM) baseSource.push({ key: 'emailService', label: SessionSourceMap['emailService'], value: 'emailService' })
      this.sourceList = baseSource
      this.currentSource = this.sourceList[0]
    }
  },
  computed: {
    // 高级搜索字段
    advanceSearchColumn() {
      return [
        ...getAdvancedFields(this, { AllPutChannel: this.AllPutChannel }),
      ];
    },
    allowImView() {
      return this.globalIsHaveImViewDetailAuth
    },
    // 邮件客服灰度
    isOpenMailIM() {
      return true
    },
  },
  components: {
    [BaseSearchDrawer.name]: BaseSearchDrawer,
    [BaseSearchPanel.name]: BaseSearchPanel,
    SearchList,
    Avatar,
  },
  mounted() {
    this.setSourceList();
    this.getAllPutChannel();
    // this.search();

    document.addEventListener('click', this.hidePopover);
  },
  destroyed () {
    document.removeEventListener('click', this.hidePopover);
  },
  watch: {
    customerList(newValue) {
      // 未选择时，默认第一个
      if (this.isactive === -1 && newValue.length) {
        // 开启窗口，异步原因。第一次id存放于sessionStorage
        if (sessionStorage.getItem('BubbleData')) {
          let BubbleData = JSON.parse(sessionStorage.getItem('BubbleData'));
          sessionStorage.removeItem('BubbleData');

          this.customerList.map((item, index) => {
            if (item.id === BubbleData.id) {
              this.clickCustomer(item, index);
              return;
            }
          });
        } else {
          this.clickCustomer(newValue[0], 0);
        }
      }
    },
    linePopoverShow(newValue) {
      if (newValue) {
        this.timer = setInterval(() => {
          this.currentTime = new Date();
        }, 1000);
      }
    },
  },
};
</script>
<style lang="scss" scoped>
.el-input__inner {
  font-size: 14px;
  font-weight: 400;
}
.el-input__inner::placeholder {
  font-size: 14px !important;
  font-weight: 400 !important;
}
.el-popover {
  padding: 0 !important;
}
</style>
<style lang="scss" scoped>
.conversation-card {
  display: flex;
  width: 100%;
  height: 58px;
  justify-content: space-around;
  margin-top: 50px;

  &-item {
    display: flex;
    align-items: center;
    flex-direction: column;
    font-size: 12px;
    color: #8C8C8C;
    padding-top: 5px;

    span:first-child {
      font-size: 14px;
      font-weight: 700;
      color: #262626;
      margin-bottom: 5px;
    }
  }

  .active:hover {
    cursor: pointer;
    color: $color-primary-light-6;

    span:first-child {
      color: $color-primary-light-6;
    }
  }
}
.customer-wrap {
  background: #fff;
  width: 298px;
  overflow-y: auto;
  border-top-left-radius: 4px;
  border-bottom-left-radius: 4px;
  border-right: 1px solid #e8e8e8;
}
.custom-title {
  position: fixed;
  width: 298px;
  height: 48px;
  display: flex;
  align-items: center;
  margin: 0;
  padding-left: 12px;
  font-weight: 600;
  color: #262626;
  font-size: 16px;
  background: #fff;
  z-index: 10;
  border-top-left-radius: 4px;
  border-bottom-left-radius: 4px;
  border-right: 1px solid #e8e8e8;
  .quickSearch {
    font-weight: normal;
    height: 100%;
    width: 75px;
    color: #595959;
    display: flex;
    align-items: center;
    ::v-deep .el-dropdown {
      max-width: 75px;
      @include text-ellipsis();
    }
  }
}
.wrap {
  display: block;
  .wrap-title {
    width: 100%;
    height: 30px;
    line-height: 30px;
    padding-left: 12px;
    background: #F7F8F8;
    font-size: 14px;
    color: #595959;
  }

  .customer-item {
    position: relative;
    border: 1px solid #fff;
    border-left: 3px solid #fff;
    display: flex;
    align-items: center;
    height: 76px;
    .icon {
      vertical-align: initial;
    }
    .im-delete {
      display: none;
      position: absolute;
      top: 50%;
      left: 0px;
      transform: translateY(-50%);
      i {
        font-size: 10px;
        margin-top: 5px;
        margin-left: 3px;
        color: #000;
        opacity: 0.25;
      }
    }
    img {
      width: 40px;
      height: 40px;
      margin-left: 20px;
      margin-right: 8px;
    }
    .item-info {
      position: relative;
      font-size: 14px;
      height: 100%;
      flex: 1;
      .im-name {
        display: flex;
        align-items: center;
        width: 100%;
        .user-name {
          max-width: 100px;
          @include text-ellipsis(); 
        }
        .tag-icon {
          margin-left: 5px;
          &.icon-weixin5 {
            color: #20cc62
          }
          &.icon-mail-fill1 {
            color: #03AEFD;
          }
        }
        position: absolute;
        height: 22px;
        color: #000000;
        top: 16px;
        left: 0px;
        .im-recentTime {
          position: absolute;
          right: 9px;
          top: 2px;
          font-size: 12px;
          color: #bfbfbf;
        }
      }
      .im-recentMessage {
        position: absolute;
        color: #bfbfbf;
        left: 0px;
        top: 42px;
        font-size: 12px;
        max-width: 136px;
        @include text-ellipsis();
      }
      .tag-box {
          display: flex;
          flex-direction: column;
          position: absolute;
          right: 9px;
          top:38px;
          .tag {
            margin-left: 4px;
            font-size: 12px;
            height: 20px;
            display: flex;
            align-items: center;
          span {
            transform: scale(0.9);
            display: inline-block;
          }
          &.tag-ygq {
            color: #ff9100;
            background: #fff3e0;
            border-radius: 10px;
            border: 1px solid #ffe0b2;
            padding: 2px 6px;
          }
          &.tag-yjs {
            color: #ff4d4f;
            background: #fff1f0;
            border-radius: 10px;
            border: 1px solid #ffccc7;
            padding: 2px 6px;
            margin-bottom: 5px;
          }
        }
      }
    }
    .im-msg {
      left: 44px;
      top: 12px;
      color: #fff;
      font-size: 12px;
      text-align: center;
      line-height: 20px;
      height: 20px;
      background: #f86137;
      position: absolute;
    }
    .im-small-count {
      width: 20px;
      border-radius: 50%;
    }
    .im-big-count {
      width: 38px;
      border-radius: 10px;
    }
  }
  .customer-item:hover .im-delete {
    display: block;
  }
  .customer-item:hover,
  .addColor {
    cursor: pointer;
    background: #f6f6f6;
    // border: 1px solid #eee;
    border-left: 3px solid #f6f6f6;
  }
  .addColor:hover {
    border-left: 3px solid $color-primary-light-6;
  }
  .addColor {
    border-left: 3px solid $color-primary-light-6;
  }
}
.customer-item:last-child {
  // border-bottom: 1px solid #eee;
}
.default {
  height: calc(100% - 78px);
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;

  .default-img {
    img {
      width: 160px;
      height: 160px;
    }
  }
  .default-msg {
    margin-top: 8px;
    color: $text-color-regular;
  }
}
.filter {
  cursor: pointer;
  color: #8c8c8c;
  margin-left: 5px;
}
.filter:hover {
  color: $color-primary-light-6;
}
.Topping {
  width: 0;
  height: 0;
  position: absolute;
  right: 0;
  top: 0;
  border-top: 8px solid #bde7ff;
  border-right: 8px solid #bde7ff;
  border-bottom: 8px solid transparent;
  border-left: 8px solid transparent;
}
.filterBox {
  flex: 1 0 auto;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}
.load-more {
  text-align: center;
  height: 20px;
  cursor: pointer;
}

.line-popover {
  .highlight {
    color: #FAAD14;
  }

  .line-item {
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-top: 12px;

    div {
      display: flex;
      align-items: center;
      max-width: 60%;

      img {
        width: 20px;
        height: 20px;
        margin-right: 8px;
      }

     .name {
        width: 70%;
        @include text-ellipsis;
      }

      .el-button {
        margin-left: 5px;
      }
    }
  }
}
</style>
<style lang="scss">
.search-popover {
  height: 400px;
  overflow: auto;
}
.conversation-popover {
  max-height: 600px;
  overflow: auto;
}
.im-operation-list{
  min-width: 110px !important;
  .menu_item__available:hover {
    background: $color-primary-light-1 !important;
    color: $color-primary-light-6 !important;
  }
}
</style>
